package edu.gatech.wms.views;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import edu.gatech.wms.R;
import edu.gatech.wms.controllers.ItemManager;
import edu.gatech.wms.controllers.Login;
import edu.gatech.wms.controllers.UserManager;
import edu.gatech.wms.models.DonatedItem;
import edu.gatech.wms.models.FoundItem;
import edu.gatech.wms.models.ItemType;
import edu.gatech.wms.models.LostItem;

public class EditItemActivity extends Activity {
	private int id, activeUserId;
	private EditText name, location, description;
	private TextView date;
	private RadioGroup radioGroup;
	private CheckBox c1,c2, c3, c4, c5, c6;
	private Address itemAddress;
	private ImageButton itemPic;
	private static final int REQUEST_CODE = 0;
	private Bitmap bitmap;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_item);
		
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		activeUserId = prefs.getInt(Login.ACTIVE_KEY, 0);
		
		Intent i = getIntent();
		id = i.getIntExtra(Login.ITEM_KEY, 0); // ID if Item Object
		
		itemPic = (ImageButton) findViewById(R.id.edit_item_upload_image);
		name = (EditText) findViewById(R.id.edit_item_name);
		location = (EditText) findViewById(R.id.edit_item_location);
		date = (TextView) findViewById(R.id.edit_item_date);
		date.setText("Date: " + ItemManager.getItemCreationDate(id));
		description = (EditText) findViewById(R.id.edit_item_description);
		TextView ownerInfo = (TextView) findViewById(R.id.edit_item_OwnerInfo);
		TextView ownerInfoTitle =  (TextView) findViewById(R.id.edit_item_OwnerInfoTitle);
		radioGroup = (RadioGroup) findViewById(R.id.edit_item_radioGroup);
		c1 = (CheckBox) findViewById(R.id.edit_item_checkBox_1);
		c2 = (CheckBox) findViewById(R.id.edit_item_checkBox_2);
		c3 = (CheckBox) findViewById(R.id.edit_item_checkBox_3);
		c4 = (CheckBox) findViewById(R.id.edit_item_checkBox_4);
		c5 = (CheckBox) findViewById(R.id.edit_item_checkBox_5);
		c6 = (CheckBox) findViewById(R.id.edit_item_checkBox_6);
		
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(name.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(location.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(description.getWindowToken(), 0);
		
		itemPic.setImageBitmap(ItemManager.getItemImage(id));
		itemPic.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v) 
			{
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				intent.addCategory(Intent.CATEGORY_OPENABLE);
				startActivityForResult(intent, REQUEST_CODE);
			}
		});
		
		// It looks like OwnerID Number isn't set correctly...
		int itemOwnerID = ItemManager.getItemOwnerId(id);
		//Toast.makeText(getApplicationContext(), "OwnerID: " + itemOwnerID , Toast.LENGTH_SHORT).show();
		if ( activeUserId != itemOwnerID ) {
			findViewById(R.id.edit_item_cancel).setVisibility(View.GONE);
			findViewById(R.id.edit_item_delete).setVisibility(View.GONE);
			findViewById(R.id.edit_item_update).setVisibility(View.GONE);
			name.setFocusable(false);
			name.setEnabled(false);
			location.setFocusable(false);
			location.setEnabled(false);
			description.setFocusable(false);
			description.setEnabled(false);
			for(int j = 0; j < radioGroup.getChildCount(); j++){
	            ((RadioButton)radioGroup.getChildAt(j)).setEnabled(false);
	        }
			c1.setFocusable(false);
			c1.setEnabled(false);
			c2.setFocusable(false);
			c2.setEnabled(false);
			c3.setFocusable(false);
			c3.setEnabled(false);
			c4.setFocusable(false);
			c4.setEnabled(false);
			c5.setFocusable(false);
			c5.setEnabled(false);
			c6.setFocusable(false);
			c6.setEnabled(false);
			itemPic.setEnabled(false);
			itemPic.setFocusable(false);
			//ownerInfo.setEnabled(false);
			ownerInfo.setText(UserManager.getUserFullName(itemOwnerID) + "\n"
					+ UserManager.getUserContact(itemOwnerID));
		} else {
			ownerInfo.setVisibility(View.GONE);
			ownerInfoTitle.setVisibility(View.GONE);
		}
		
		itemAddress = ItemManager.getLocation(id);
		if (itemAddress != null) {
			location.setText(ItemManager.getLocation(id).getAddressLine(0));
			
		}
		
		name.setText(ItemManager.getItemName(id));
		description.setText(ItemManager.getItemDescription(id));
		ItemType itemType = ItemManager.getItemType(id);
		List<String> categories = ItemManager.getItemCategories(id);
		
		for ( String category : categories ) {
			if ( category.equals("Electronic") ) {
				c1.setChecked(true);
			} else if ( category.equals("Furniture") ) {
				c2.setChecked(true);
			} else if ( category.equals("Photo") ) {
				c3.setChecked(true);
			} else if ( category.equals("Toy") ) {
				c4.setChecked(true);
			} else if ( category.equals("Jewelry") ) {
				c5.setChecked(true);
			} else if ( category.equals("Other") ) {
				c6.setChecked(true);
			}
		}
		
		if ( itemType instanceof LostItem ) {
			radioGroup.check(R.id.edit_item_radioBtn_lost);
		} else if ( itemType instanceof FoundItem ) {
			radioGroup.check(R.id.edit_item_radioBtn_found);
		} else if ( itemType instanceof DonatedItem ) {
			radioGroup.check(R.id.edit_item_radioBtn_donation);
		}
		
		findViewById(R.id.edit_item_update).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						View focusView = null;
						boolean cancel = true;
						
						int radioGroupId = radioGroup.getCheckedRadioButtonId();
						
						ItemType itemType = null;
						switch ( radioGroupId ) {
							case R.id.edit_item_radioBtn_lost:
								itemType = new LostItem();
								break;
							case R.id.edit_item_radioBtn_found:
								itemType = new FoundItem();
								break;
							case R.id.edit_item_radioBtn_donation:
								itemType = new DonatedItem();
								break;
						}
						
						String _itemName = name.getText().toString();
						String _location = location.getText().toString();
						String _description = description.getText().toString();
						List<String> categories = new ArrayList<String>();
						
						if ( c1.isChecked() ) {
							categories.add(c1.getText().toString());
						}
						
						if ( c2.isChecked() ) {
							categories.add(c2.getText().toString());
						}
						
						if ( c3.isChecked() ) {
							categories.add(c3.getText().toString());
						}
						
						if ( c4.isChecked() ) {
							categories.add(c4.getText().toString());
						}
						
						if ( c5.isChecked() ) {
							categories.add(c5.getText().toString());
						}
						
						if ( c6.isChecked() ) {
							categories.add(c6.getText().toString());
						}
						
						if ( TextUtils.isEmpty(_itemName) ) {
							name.setError(getString(R.string.error_field_required));
							focusView = name;
							cancel = false;
						}
						
						if ( TextUtils.isEmpty(_location) ) {
							location.setError(getString(R.string.error_field_required));
							focusView = location;
							cancel = false;
						} else {
							Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
							if(Geocoder.isPresent()) {
								try {
									List<Address> results;
									int timeout = 0;
									do {
										results = geocoder.getFromLocationName(_location, 3);
										timeout++;
									}	while ( results.size() == 0 && timeout < 500);
									if (results.size() > 0) {
										itemAddress = results.get(0);
									}
								} catch (IndexOutOfBoundsException e) {
									Toast.makeText(getApplicationContext(), "Your GeoCoder is poorly coded!", Toast.LENGTH_SHORT).show();
								} catch (IOException e) {
									Toast.makeText(getApplicationContext(), "Your GeoCoder is poorly coded!", Toast.LENGTH_SHORT).show();
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							} else {
								itemAddress = new Address(Locale.getDefault());
								itemAddress.setAddressLine(0, _location);
							}
						} 
						
						if ( categories.isEmpty() ) {
							Toast.makeText(getBaseContext(),"Please select at least one category",Toast.LENGTH_LONG).show();
							cancel = false;
						}
						
						if ( cancel ) {
							ItemManager.updateItem(_itemName, itemType, id,
									_description, bitmap, activeUserId, itemAddress,
									categories);
							finish();
						} else {
							focusView.requestFocus();
						}
						
					}
				});
		
		findViewById(R.id.edit_item_cancel).setOnClickListener(
				new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						finish();
					}
				});
		findViewById(R.id.edit_item_delete).setOnClickListener(
				new View.OnClickListener() {
					
					public void onClick(View v) {
						ItemManager.deleteItem(id);
						finish();
					}
				});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		if(REQUEST_CODE == requestCode && resultCode == Activity.RESULT_OK)
		{
			try
			{
				if(bitmap != null)
					bitmap.recycle();
				InputStream inStream = getContentResolver().openInputStream(data.getData());
				bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeStream(inStream), itemPic.getWidth(), itemPic.getHeight(), true);
				inStream.close();
				itemPic.setImageBitmap(bitmap);
			}
			catch(FileNotFoundException e)
			{
				e.printStackTrace();
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}
}
